import asyncio
import logging
from typing import Optional, Tuple

from src.config.settings import DHT_PORT
from src.core.message_dispatcher import MessageDispatcher
from src.core.network_manage import NetworkManage
from src.core.query_handler import QueryHandler
from src.core.response_handler import ResponseHandler
from src.globals.globals import GlobalManage
from src.handle.event_handler.handler_manager import HandlerManager
from src.log.logger import setup_logger
from src.model.event.events import DHTBootstrapStart
from src.routing.routing_table import RoutingTable
from src.rpc.KRPC import KRPC


class Crawler(asyncio.DatagramProtocol):

    def __init__(self,host: str = '0.0.0.0', port: int = DHT_PORT):

        self.logger: logging.Logger = setup_logger('Crawler')
        self.port : int = port
        self.ip : str = host

        # 运行状态标志，用于控制嗅探器的启动和停止
        self.running: bool = False

        self.network_manage: Optional[NetworkManage] = None

        self.handler_manager: Optional[HandlerManager] = None

        self.krpc: Optional[KRPC] = None

        self.unique_id: Optional[str] = None

        self.message_dispatcher: Optional[MessageDispatcher] = None
    

    async def start_crawler(self):
        try:
            self.running = True

            self.unique_id = self.get_key()

            self.network_manage = NetworkManage(self.ip, self.port)
            GlobalManage.get_instance().add_network_manage(self.unique_id,self.network_manage)


            self.krpc = KRPC(self.network_manage)
            GlobalManage.get_instance().add_krpc(self.unique_id,self.krpc)

            self.routing_table = RoutingTable(self.network_manage.node_id)
            GlobalManage.get_instance().add_routing_table(self.unique_id,self.routing_table)



            self.logger.info('准备全局管理器初始')
            self.handler_manager = HandlerManager(GlobalManage.get_instance())
            self.handler_manager.init_handlers()
            self.logger.info('准备处理器初始化完成')


            self.logger.info('网络管理器启动成功')
            await self.network_manage.start_server(self)

            self.logger.info(f"DHT爬虫启动成功，监听端口: {self.port}")

            # 发布引导节点启动事件
            GlobalManage.get_instance().publish_event(DHTBootstrapStart(unique_id=self.unique_id))

            # 启动调度器
            GlobalManage.get_instance().start_scheduler()

            self.message_dispatcher = MessageDispatcher(response_handler=ResponseHandler(self.network_manage.transaction_holder, self.unique_id), query_handler=QueryHandler(self.network_manage.transaction_holder, self.unique_id))

            
        except Exception as e:
            self.logger.error(f"DHT爬虫启动失败: {e}")
            await self.network_manage.stop_server()
            self.running = False

    async def stop_crawler(self):
        self.running = False
        await self.network_manage.stop_server()
        self.logger.info("DHT爬虫已停止")

    def get_key(self) -> str:
        return f'{self.ip}:{self.port}'

    def datagram_received(self, data: bytes, addr: Tuple[str, int]):
        self.logger.debug(f"收到数据: {data} 来自: {addr}")
        self.message_dispatcher.dispatch(data,addr)
        
    